package com.wuhaha.a1911_demo.ui.Login;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import androidx.arch.core.executor.ArchTaskExecutor;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.wuhaha.a1911_demo.model.UserMessage;
import com.wuhaha.a1911_demo.utlis.AppGlobals;
import com.wuhaha.libnetwork2.cache.CacheManage;
import com.wuhaha.libnetwork2.network.ApiResponse;
import com.wuhaha.libnetwork2.network.ApiServices;
import com.wuhaha.libnetwork2.network.JsonCallback;

public
/**
 * Create date: On 2022/8/22
 */
//统一存储用户信息
class UserManager {
    private static final String KEY_CACHE_USER = "cache_user";
    private static UserManager mUserManager = new UserManager();
    private MutableLiveData<UserMessage> userLiveData;
    private UserMessage userMessage;

    public static UserManager get() {
        return mUserManager;
    }

    private UserManager() {
        UserMessage cache = (UserMessage) CacheManage.getCache(KEY_CACHE_USER);
        if (cache != null && cache.expires_time > System.currentTimeMillis()) {
            userMessage = cache;
        }
    }

    //持续化用户信息
    public void saves(UserMessage user) {
        userMessage = user;
        CacheManage.save(KEY_CACHE_USER, user);
        if (getUserLiveData().hasObservers()) {
            //发送事件
            getUserLiveData().postValue(user);
        }
    }
    //监听login的结果
    public LiveData<UserMessage> login(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
        return getUserLiveData();
    }

    //判断是否登录
    public boolean isLogin(){
        return userMessage == null ? false : userMessage.expires_time > System.currentTimeMillis();
    }
    //当前登录者用户信息
    public UserMessage getUser() {
        return isLogin() ? userMessage : null;
    }

    public long getUserId() {
        return isLogin() ? userMessage.userId : 0;
    }

    public LiveData<UserMessage> refresh(){
        if (!isLogin()){
            return login(AppGlobals.getApplication());
        }
        MutableLiveData<UserMessage> liveData = new MutableLiveData<>();
        ApiServices.get("/user/query")
                .addParam("userId", getUserId())
                .execute(new JsonCallback<UserMessage>() {
                    @Override
                    public void onSuccess(ApiResponse<UserMessage> response) {
                        saves(response.body);
                        liveData.postValue(getUser());
                    }

                    @SuppressLint("RestrictedApi")
                    @Override
                    public void onError(ApiResponse<UserMessage> response) {
                        ArchTaskExecutor.getMainThreadExecutor().execute(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(AppGlobals.getApplication(), response.message, Toast.LENGTH_SHORT).show();
                            }
                        });
                        liveData.postValue(null);
                    }
                });
        return liveData;
    }

    /**
     * bugfix:  liveData默认情况下是支持黏性事件的，即之前已经发送了一条消息，当有新的observer注册进来的时候，也会把先前的消息发送给他，
     * 就造成了{ }死循环
     * 那有两种解决方法
     * 1.我们在退出登录的时候，把livedata置为空，或者将其内的数据置为null
     * 2.利用我们改造的stickyLiveData来发送这个登录成功的事件
     * 我们选择第一种,把livedata置为空
     */
    public void logout() {
        CacheManage.delete(KEY_CACHE_USER, userMessage);
        userMessage = null;
        userLiveData = null;
    }

    private MutableLiveData<UserMessage> getUserLiveData() {
        if (userLiveData == null) {
            userLiveData = new MutableLiveData<>();
        }
        return userLiveData;
    }


}
